<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="mySchema" v-slot="{errors}">
    <!-- 请输入用户名 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{err:errors.account}" v-model="form.account" name="account" class="input" placeholder="请输入用户名" type="text"/>
      </div>
      <div v-if="errors.account" class="error">{{errors.account}}</div>
    </div>
    <!-- 输入手机号 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" v-model="form.mobile" name="mobile" class="input" placeholder="请输入手机号" type="text"/>
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
    </div>
    <!-- 输入验证码 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" v-model="form.code" name="code" class="input" placeholder="请输入验证码" type="text"/>
        <span class="code" @click="send()">
          {{time===0?'发送验证码':`${time}秒后再发送`}}
        </span>
      </div>
      <div v-if="errors.code" class="error">{{errors.code}}</div>
    </div>
    <!-- 输入密码 -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.password}" v-model="form.password" name="password" class="input" placeholder="请输入密码" type="password"/>
      </div>
      <div v-if="errors.password" class="error">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.rePassword}" v-model="form.rePassword" name="rePassword" class="input" placeholder="请确认密码" type="password"/>
      </div>
      <div v-if="errors.rePassword" class="error">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit()">立即提交</a>
  </Form>
</template>

<script>
import schema from '@/utils/vee-validate-schema'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user.js'
import { Form, Field } from 'vee-validate'
import { reactive, ref } from '@vue/reactivity'
import { onUnmounted } from '@vue/runtime-core'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 1.表单校验（添加两种校验规则：用户名是否存在？再次出输入密码是否一致）
    const mySchema = {
      account: schema.accountAPI,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }
    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    // 2.发送短信验证码,定义发送接口API
    // 3.完善信息
    const time = ref(0)
    const formCom = ref(null)
    const { pause, resume } = useIntervalFn(() => {
      // 回调函数 时间减少到0时就停止定时器
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })

    onUnmounted(() => {
      pause()
    })
    // 发送短信
    const send = async () => {
      // console.log('已经点击')
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        // console.log('通过验证')
        // console.log(time.value)
        // 没有倒计时才可以发送
        if (time.value === 0) {
          // console.log('没有定时器')
          // console.log(userAccountLoginMsg(form.mobile))
          await userQQPatchCode(form.mobile)
          Message({ type: 'success', text: '短信验证码已发送' })
          time.value = 60
          // 开始定时器
          // console.log(time.value)
          resume()
        }
      } else {
        // 失败 使用vee的错误函数setFieldError(字段名称，错误信息)显示错误信息
        formCom.value.setFieldError('mobile', valid)
      }
    }

    // 立即提交
    const store = useStore()
    const router = useRouter()
    const submit = () => {
      const valid = formCom.value.validate()
      if (valid) {
        userQQPatchLogin({
          unionId: props.unionId,
          ...form
        }).then(data => {
          // 实现和之前登录一样的逻辑
          const { id, account, avater, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avater, mobile, nickname, token })
          store.dispatch('cart/mergeCart').then(() => {
            // 2.跳转到来源页或者首页（已经在vuex中保存的回跳地址）
            router.push(store.state.user.redirectUrl)
            // 3.提示信息
            Message({ type: 'success', text: 'QQ登录成功' })
          })
        }).catch(e => {
          console.log(e)
          Message({ type: 'error', text: '登录失败' })
        })
      }
    }
    return { mySchema, form, send, formCom, time, submit }
  }
}
</script>

<style lang="less" scoped>
.code{
  position: absolute;
  right: 0;
  top:0;
  line-height: 50px;
  width: 95px;
  color:#999;
  &:hover{
    cursor:pointer;
  }
}
</style>
